package com.acxmpp.common.util.net;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.content.Context;
import android.net.ConnectivityManager;

import com.acxmpp.common.domain.net.HttpContentType;
import com.acxmpp.common.domain.net.HttpMethod;
import com.acxmpp.common.util.LogUtil;
import com.acxmpp.common.util.StringUtil;
import com.acxmpp.common.util.io.StreamUtil;

/**
 * @author frank
 *
 */
public class HttpUtil {
	private static final String TAG = HttpUtil.class.getSimpleName();
	private static final String UTF8_ENCODING = "UTF-8";

	/**
	 * @param path 请求URL
	 * @param method (HttpMethod.GET, HttpMethod.POST, HttpMethod.DELETE)
	 * @param token Authorization信息
	 * @param type 类型Content-Type: (HttpContentType.JSON, HttpContentType.XML)
	 * @param request 请求参数
	 * @return
	 * @throws Exception
	 */
	public static String sendRequest(String path, HttpMethod method, String token, HttpContentType type, String request) throws Exception {
		String result = null;

		HttpURLConnection conn = (HttpURLConnection) new URL(path).openConnection();
		LogUtil.e(TAG, String.format("sendRequest (url: %s; Extra: %s)", new URL(path).toString(), request));

		conn.setDoInput(true);
		conn.setDoOutput(true);
		conn.setRequestMethod(method.getValue());
		conn.setRequestProperty("Authorization", token);
		conn.setRequestProperty("Content-Type", type.getValue());
		conn.setConnectTimeout(8000);
		conn.setReadTimeout(25000);

		OutputStream out = null;
		if (!StringUtil.isNullOrEmpty(request)) {
			out = conn.getOutputStream();
			out.write(request.getBytes(UTF8_ENCODING));
			out.flush();
		}

		InputStream in = conn.getInputStream();
		result = StreamUtil.readStreamAsString(in).replaceAll("\\\\r", ""); 
		// TODO need check
		// result = StreamUtil.readStream(in).toString();

		if (out != null)
			out.close();
		if (in != null)
			in.close();

		if (!StringUtil.isNullOrEmpty(result)) {
			LogUtil.e(TAG, String.format("Response: %s", result));
		}

		return result;
	}

	/**
	 * 网络判断
	 * 
	 * @return 返回true为有网络
	 */
	public static boolean netWorkStatus(Context context) {
		boolean netSataus = false;

		ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		connManager.getActiveNetworkInfo();
		if (connManager.getActiveNetworkInfo() != null) {
			netSataus = connManager.getActiveNetworkInfo().isAvailable();
		}

		return netSataus;
	}
}
